﻿<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

<div id="liveSearch"></div>

@using (Ajax.BeginForm("Article", "Search", new {}, new AjaxOptions() { OnSuccess = "LiveSearch", HttpMethod = "post" }, new { id = "searchBox" }))
{
    <div class="wrapper">
		<input type="text" id="search" name="search" placeholder="Search" onkeyup="SearchTextChanged($(this))" />
		<button type="submit" class="search_btn"><img src="@Url.Content("~/Content/images/search.png")" title="Search" /></button>
	</div>
}

<script type="text/javascript">
    function LiveSearch(e) {
        var updateTarget = $('#liveSearch');
        updateTarget.html('');

        for (var i = 0; i < e.length; i++) {
            var a = $('<a href="@Url.Content("~/Article/")' + e[i] + '">' + e[i] + '</a>');
            updateTarget.append(a);
        }

        if (e.length < 1) {
            $('#liveSearch').fadeOut();
        }
        
        if(!updateTarget.is(':visible')) {
            updateTarget.fadeIn();
        }

        var aClose = $('<a href="#">close</a>');
        aClose.css('text-align', 'right');
        aClose.css('font-weight', 'bold');
        aClose.click(function () {
            $('#liveSearch').fadeOut();
        });
        updateTarget.append(aClose);
    }

    function SearchTextChanged(sender) {
        if (sender.val().length > 3) {
            $('#searchBox').submit();
        }
        else {
            $('#liveSearch').fadeOut();
        }
    }
</script>